/**
 *******************************************************************************
 * @FileName  : critical.c
 * @Author    : GaoQiu
 * @CreateDate: 2020-05-18
 * @Copyright : Copyright(C) GaoQiu
 *              All Rights Reserved.
 *******************************************************************************
 *
 * The information contained herein is confidential and proprietary property of
 * GaoQiu and is available under the terms of Commercial License Agreement
 * between GaoQiu and the licensee in separate contract or the terms described
 * here-in.
 *
 * This heading MUST NOT be removed from this file.
 *
 * Licensees are granted free, non-transferable use of the information in this
 * file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
 *
 *******************************************************************************
 */
#include "critical.h"

/* Critical Section(CS) nesting level. */
uint8_t csNesting = 0;

#define reg(x)               (*(volatile unsigned char*)(0x800000 + (x)))
#define irq_en_reg           reg(0x643)

inline uint8_t disable_irq(void)
{
	uint8_t cpu_state = irq_en_reg;
	irq_en_reg = 0;
	return cpu_state;
}

inline void enable_irq(uint8_t state)
{
	irq_en_reg = state;
}

RAM_CODE uint8_t EnterCritical(void)
{
	uint8_t state = 0;
	if(csNesting == 0){
		state = disable_irq();
	}
	csNesting++;

	return state;
}

RAM_CODE void ExitCritical(uint8_t state)
{
	csNesting--;
	if(csNesting == 0){
		enable_irq(state);
	}
}

